package org.ma5d;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class HelloTest {

    public static void main(String[] args) {
        // 1.定义jobDetail，对MyJob进行包装，job1是任务名称，group1是任务分组
        JobDetail job = JobBuilder.newJob(HelloJob.class)
                .withIdentity("job1", "jGroup1")
                .build();

        // 2.定义触发器，trigger1是触发器的名称，group1是触发器的分组
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1", "tGroup1")
                // 立刻执行
                .startNow()
                // 触发策略，用简单的触发策略，就是按照时间间隔执行
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        // 1秒执行一次
                        .withIntervalInSeconds(1)
                        // 一直重复
                        .repeatForever())
                .build();

        try {
            // 3.定义调度器
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            // 设置任务和触发器，由触发器进行分派任务
            scheduler.scheduleJob(job, trigger);
            scheduler.start();

            // 让主线程延迟执行，scheduler如果shutdown，则所有的定时任务会取消。
            TimeUnit.SECONDS.sleep(20);
            scheduler.shutdown();
        } catch (SchedulerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static class HelloJob implements Job {
        private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        @Override
        public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
            System.out.println("执行任务:" + sdf.format(new Date()));
        }
    }
}
